/*
 * LevelContext.cpp
 *
 *  Created on: 22/04/2011
 *      Author: ehpalumbo
 */

#include "LevelContext.h"

namespace contexts {


LevelContext::LevelContext(vector<DataUnit*>& dataUnits) {
	this->units = new vector<ContextUnit*>(dataUnits.size() + 1);
	// Create required context units.
	for (unsigned int i = 0; i < dataUnits.size(); i++) {
		this->units->at(i) = new ContextUnit(*(dataUnits[i]), *this);
	}
	// Don't forget to add the escape.
	this->units->at(dataUnits.size()) = new ContextUnit(*new Escape, *this);
}

unsigned int LevelContext::getTotalFrequency() {
	unsigned int totalFrequency = 0;
	for (unsigned int i = 0; i < this->units->size(); i++) {
		totalFrequency += (this->units->at(i))->getFrequency();
	}
	return totalFrequency;
}

vector<ContextUnit*>& LevelContext::getUnits() {
	return *(this->units);
}

ContextUnit& LevelContext::getContextUnitFor(DataUnit& dataUnit){
	/*LA ONDA ES Q ME DEVUELVA EL CONTEXT UNIT Q LE TOCA O EL ESCAPE
		y que el struct model se de cuenta que si da escape tiene q ir al prox nivel*/
	// Search the corresponding context unit.
	for (unsigned int i = 0; i < this->units->size(); i++) {
		if ((this->units->at(i)->getDataUnit()) == dataUnit) {
			return (*this->units->at(i));
		}
	}
	// If we're here, it means that the context unit isn't here, so we return the escape one.
	return this->getEscape();
}

//Chequear que en el caso del último nivel el caracter no es un escape, sino el eof
ContextUnit& LevelContext::getEscape() {
	return *(this->units->back());
}


LevelContext::~LevelContext() {
	// Delete created context units.
	for (unsigned int i = 0; i < this->units->size(); i++) {
		delete &(this->units->at(i));
	}
	// Delete container.
	delete this->units;
}


}
